<template>
    <view class="azm-leaderboard-components h100 bg-white overflow-hidden">
        <mescroll-uni ref="mescrollRef" @init="mescrollInit" @down="downCallback" :fixed="true"
                      @up="upCallback" :down="downOption" :up="upOption" :top="top" :bottom="bottom">
            <view class="azm-herder flex align-center">
                <view class="left flex align-center" v-if="userInfo.user_id"
                      @tap.stop="handleTapSelect">
                    <text class="azm-name">{{selectData.name || userInfo.nickname}}</text>
                    <text class="tlIcon-date_extend azm-icon"></text>
                </view>
                <scroll-view scroll-x class="flex-sub right azm-tap-btns" v-if="!customize">
                    <view class="flex align-center justify-end">
                        <button hover-class="none"
                                class="cu-btn sm" :class="index === curIndex?'bg-blue':'bg-gray'"
                                v-for="(item,index) in taps" @tap.stop="handleSwitchFilter(index)"
                                :key="item">{{item}}
                        </button>
                    </view>
                </scroll-view>
                <view class="flex align-center justify-end flex-sub azm-customize" v-else
                      @tap.stop="handleCalendarSelectDate(2)">
                    <view class="picker flex align-center">
                        <text>{{filterData.start_time | ic_date_format_filter("YYYY-MM-DD")}}</text>
                        <text class="tlIcon-date_extend azm-icon"></text>
                    </view>
                    <text class="azm-margin-left-3 azm-margin-right-8">至</text>
                    <view class="picker flex align-center">
                        <text>{{filterData.end_time | ic_date_format_filter("YYYY-MM-DD")}}</text>
                        <text class="tlIcon-date_extend azm-icon"></text>
                    </view>
                    <view class="h100 flex align-center">
                        <text class="tlIcon-delete azm-close-icon"
                              @tap.stop="handleCloseSelectTime"></text>
                    </view>
                </view>
            </view>
            <view class="azm-interval-height"></view>
            <view class="w100">
                <scroll-view scroll-x class="azm-top bg-white nav"
                             scroll-with-animation :scrollLeft="scrollLeft">
                    <view class="cu-item" v-for="(item,index) in typeTabs" :key="index">
                        <button class="cu-btn round azm-tabs-item bg-white"
                                :class="{active:index === TabCur}" hover-class="none"
                                @tap.stop="handleSwitchTab($event,index)">{{item.name}}
                        </button>
                    </view>
                </scroll-view>
            </view>
            <view class="flex align-center justify-between bg-white azm-padding-top-7">
                <view class="azm-txt-left">成员</view>
                <view class="azm-txt-right">客户数</view>
            </view>
            <view class="cu-list menu sm-border azm-rank show-last-child">
                <view class="cu-item" v-for="(item,index) in dataList" :key="index">
                    <view class="cu-avatar round lg">
                        <image lazy-load class="azm-avatar" :src="item.avatar| ic_image_filter" mode="aspectFill"
                               @error="handleImageError(item,'avatar','avatar')"></image>
                    </view>
                    <view class="content">
                        <view class="azm-nickname azm-ellipsis--l1">
                            <text>{{item.nickname || ''}}</text>
                        </view>
                        <view class="azm-desc azm-ellipsis--l1">
                            <text>
                                <text>{{ item.position || "" }}</text>
                                <!--<text v-if="item.position">· {{ item.position }}</text>-->
                            </text>
                        </view>
                    </view>
                    <view class="action">
                        <view class="azm-num azm-ellipsis--l1">
                            <text>{{item.count | ic_number_filter}}</text>
                        </view>
                        <view class="azm-sort">NO.{{index + 1}}</view>
                    </view>
                </view>
            </view>
        </mescroll-uni>
        <!--底部弹出选择-->
        <tl-calendar isFixed :minDate="calendarOpts.minDate" :maxDate="calendarOpts.maxDate"
                     :btnType="calendarOpts.btnType" :activeBgColor="calendarOpts.activeBgColor"
                     :rangeBgColor="calendarOpts.rangeBgColor" dynamic
                     :rangeColor="calendarOpts.rangeColor"
                     :startText="calendarOpts.startText" :endText="calendarOpts.endText"
                     :arrowType="calendarOpts.arrowType" :type="calendarOpts.type"
                     ref="calendar" @confirm="handleCalendarConfirm"
                     @change="handleCalendarChange" @cancel="handleCalendarCancel"></tl-calendar>
    </view>
</template>

<script>
    import { mapGetters, mapState } from 'vuex'
    import DateRangeUtilMixins from '@/mixins/dateRangeUtil'
    import tlCalendar from "@/components/tl-ui/calendar/index.vue";
    import tlNoData from "@/components/tl-ui/Abnor/no-data.vue";
    // 引入mescroll-mixins.js
    import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
    // 引入mescroll-body组件 (如已在main.js注册全局组件,则省略此步骤)
    import MescrollUni from "@/components/mescroll-uni/mescroll-uni.vue"; // 注意.vue后缀不能省
    export default {
        name: "leaderboard",
        mixins: [MescrollMixin, DateRangeUtilMixins],
        components: {MescrollUni, tlCalendar, tlNoData},
        props: {
            bottom: Number,
            top: Number,
        },
        data () {
            const currentWeek = this.$$$getLastWeek()
            return {
                calendarOpts: {
                    type: 1,
                    status: [],
                    arrowType: 1,
                    minDate: "1920-01-01",
                    maxDate: "",
                    btnType: "blue",
                    activeBgColor: "#0075FF",
                    rangeBgColor: "rgba(0, 117, 255, 0.1)",
                    rangeColor: "#0075FF",
                    startText: "开始",
                    endText: "结束",
                    result: "",
                },
                filterData: {
                    start_time: currentWeek.start_date,
                    end_time: currentWeek.end_date,
                    times: [currentWeek.start_date, currentWeek.end_date]
                },
                customize: false,//切换自定义
                // 下拉刷新的常用配置
                taps: ["累计", "昨天", "本周", "本月", "自定义"],
                curIndex: 0,
                typeTabs: [
                    {
                        name: "所有客户",
                        active: true,
                    },
                    {
                        name: "已成交客户",
                        active: false,
                    },
                    {
                        name: "锁定客户",
                        active: false,
                    },
                    {
                        name: "转发名片数",
                        active: false,
                    },
                    {
                        name: "拨打电话数",
                        active: false,
                    }
                ],
                TabCur: 0,
                scrollLeft: 0,
                mescrollBodyHeight: "",
                // 下拉刷新的常用配置
                downOption: {
                    use: true, // 是否启用下拉刷新; 默认true
                    auto: false, // 是否在初始化完毕之后自动执行下拉刷新的回调; 默认true
                    native: false // 启用系统自带的下拉组件,默认false;仅mescroll-body生效,mescroll-uni无效
                },
                // 上拉加载的常用配置
                upOption: {
                    use: true, // 是否启用上拉加载; 默认true
                    auto: false, // 是否在初始化完毕之后自动执行上拉加载的回调; 默认true
                    // isBounce: true, // 是否允许橡皮筋回弹效果, 默认不允许; 1.1.5新增
                    page: {
                        num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
                        size: 10 // 每页数据的数量,默认10
                    },
                    noMoreSize: 1, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
                    empty: {
                        tip: '暂无相关数据',
                        use: false,
                    },
                    textNoMore: "-- END --",
                    textColor: "#A2A8A8",
                },
                // 列表数据
                dataList: [],
                // 选择的对象
                selectData: {
                    name: "",
                    id: "",
                    type: 1
                }
            }
        },
        computed: {
            ...mapState({
                userInfo: state => state.System.userInfo
            })
        },
        mounted () {
            this.$nextTick(function () {
                this.setMescrollBodyHeight()
                this.handleRefresh()
            })
        },
        methods: {
            async handleRefresh () {
                const item = this.$Storage.getStorageSync('interim-leaderboard-data')
                if (this.noDataType === 1 || this.noDataType === 2) return this.$util.Login.toLogin();
                if (item && !this.$util.jude.isEmpty(item.id)) {
                    if (item.type === 1) {
                        this.selectData = item
                    } else {
                        this.selectData = item
                    }
                } else {
                    this.selectData = {
                        type: 0,
                        name: "公司团队",
                        id: 0
                    }
                    this.$Storage.setStorageSync('interim-leaderboard-data', this.selectData)
                }
                this.mescroll && this.mescroll.triggerDownScroll();
            },
            handleTapSelect () {
                this.handleToLoginLink({
                    path: "/pages/report/operate/select-branch"
                })
            },
            handleCloseSelectTime () {
                this.customize = false;
                this.isChangeTime = false;
                if (this.isChangeTime) this.handleRefresh();
                this.$refs.calendar.closeSelect();
            },
            handleSwitchFilter (index) {
                if (this.taps.length - 1 === index) {
                    this.customize = true
                    this.handleCalendarSelectDate(2);
                } else {
                    this.curIndex = index
                    this.handleRefresh()
                }
            },

            setMescrollBodyHeight () {
                let that = this;
                const SelectorQuery = uni.createSelectorQuery();
                SelectorQuery.in(this);
                const NodesRef = SelectorQuery
                    .select('.azm-leaderboard-components').boundingClientRect();
                NodesRef.exec(([a]) => {
                    if (!a) return;
                    that.mescrollBodyHeight = a.height * 2
                })
            },
            async loadData (page, page_size) {
                const info = await this.getSelectData()
                if (info === false) return Promise.resolve({});
                return this.$ajax.Chart.getRankingList(info);
            },

            // 获取切换数据
            getSelectData () {
                const self = this;
                const type = this.TabCur;
                const {dateFormat, getMonthDay, timeForMat} = this.$util
                let {isEmptyObject, isEmpty} = self.$util.jude
                let curIndex = this.curIndex;
                let filterData = this.filterData;
                let end_date = '';
                let start_date = '';
                if (this.customize === true) {
                    end_date = filterData.end_time;
                    start_date = filterData.start_time;
                } else {
                    switch (curIndex) {
                        case 1: // 昨天
                            const Yesterday = this.$$$getYesterday();
                            end_date = Yesterday.end_date
                            start_date = Yesterday.start_date
                            break;
                        case 2:
                            const currentWeek = this.$$$getCurrentWeek();
                            end_date = currentWeek.end_date
                            start_date = currentWeek.start_date
                            break;
                        case 3:
                            const currentMonth = this.$$$getCurrentMonth();
                            end_date = currentMonth.end_date
                            start_date = currentMonth.start_date
                            break;
                        default:
                            end_date = ''
                            start_date = ''
                    }
                }
                let selectData = {};
                if (self.selectData && !isEmpty(self.selectData.id)) {
                    selectData = {...self.selectData, end_date, start_date}
                } else if (self.userInfo && !isEmpty(self.userInfo.user_id)) {
                    self.selectData = {
                        id: self.userInfo.user_id,
                        name: self.userInfo.nickname,
                    }
                    selectData = {...self.selectData, end_date, start_date}
                } else {
                    return Promise.resolve(false);
                }
                return Promise.resolve({
                    ...selectData,
                    department_id: selectData.id,
                    type: type
                });
            },

            mescrollInit (mescroll) {
                this.mescroll = mescroll;
            },
            /*下拉刷新的回调, 有三种处理方式: */
            downCallback (mescroll) {
                mescroll.resetUpScroll();
            },
            /*上拉加载的回调*/
            async upCallback (mescroll) {
                const vm = this;
                const {isEmptyObject, isEmptyArray} = vm.$util.jude;
                const page = mescroll.num;
                const page_size = mescroll.size;
                const result = await vm.loadData(page, page_size);
                if (page === 1) vm.dataList = []; //如果是第一页需手动置空列表
                if (result.code === 0 && !isEmptyObject(result.data, true)) {
                    const info = result.data;
                    const curPageData = isEmptyArray(info.list) ? [] : info.list;
                    const total = info.total === 0 ? curPageData.length : info.total;
                    mescroll.endByPage(curPageData.length, total);
                    vm.dataList = vm.dataList.concat(curPageData); //追加新数据
                    mescroll.optUp.textNoMore = `- 共${total || 0}位成员 -`
                }
                mescroll.endByPage(0, 0);
                mescroll.endErr()// 联网失败的回调,隐藏下拉刷新的状态
            },

            handleSwitchTab (e, index) {
                this.TabCur = index;
                if (index === 0) {
                    this.scrollLeft = 0;
                } else {
                    this.scrollLeft = e.detail.x;
                }
                this.handleRefresh();
            },

            /********************** 日历 start ********************/
            handleCalendarSelectDate (type) {
                this.isHideCanvas = true; // 打开时候隐藏图表
                const dateFormat = this.$util.dateFormat;
                const today = dateFormat(Date.now(), "YYYY-MM-DD");
                const calendarOpts = {
                    arrowType: 1,
                    minDate: "1920-01-01",
                    maxDate: "",
                    startText: "开始",
                    endText: "结束",
                };
                switch (type) {
                    case 1:
                        calendarOpts.type = 1
                        break;
                    case 2:
                        calendarOpts.type = 2
                        calendarOpts.minDate = ""
                        calendarOpts.maxDate = today
                        break;
                    case 3:
                        calendarOpts.minDate = "2020-04-01"
                        calendarOpts.maxDate = "2020-06-08"
                        calendarOpts.type = 1
                        break;
                    case 4:
                        calendarOpts.type = 2
                        calendarOpts.btnType = "danger"
                        calendarOpts.activeBgColor = "#EB0909"
                        calendarOpts.rangeBgColor = "rgba(235,9,9,0.1)"
                        calendarOpts.rangeColor = "#EB0909"
                        calendarOpts.arrowType = 1
                        break;
                    case 5:
                        calendarOpts.type = 2
                        calendarOpts.startText = "住店"
                        calendarOpts.endText = "离店"
                        break;
                    case 6:
                        calendarOpts.arrowType = 2
                        break;
                    default:
                        break;
                }
                this.$util.mapKeys(calendarOpts, this.calendarOpts, Object.keys(this.calendarOpts))
                this.$refs.calendar.show()
            },
            handleCalendarChange (e) {
                // const {dateFormat, dateRange, timeForMat, transformDate} = this.$util
                // let endDate = timeForMat(1, e.startDate, "M");
                // endDate = timeForMat(-1, endDate, "D");
                // const flag = +(transformDate(endDate)) < Date.now();
                // if (flag) {
                //     this.calendarOpts.maxDate = dateFormat(endDate, "YYYY-MM-DD")
                // } else {
                //     this.calendarOpts.maxDate = dateFormat(Date.now(), "YYYY-MM-DD")
                // }
            },
            handleCalendarConfirm (e) {
                this.isChangeTime = true; // 是否改变时间
                this.isHideCanvas = false;
                this.calendarOpts.result = `${e.startDate} 至 ${e.endDate}`;
                this.filterData.start_time = e.startDate;
                this.filterData.end_time = e.endDate;
                this.handleRefresh();
            },
            handleCalendarCancel () {
                this.isHideCanvas = false;
                console.log("handleCalendarCancel");
                if (!this.calendarOpts.result) this.customize = false;
            }
            /********************** 日历 end ********************/
        }
    }
</script>

<style scoped lang="scss">
    .azm-leaderboard-components {
        .azm-interval-height {
            height: 5*2upx;
            background: #F5F5F5;
        }

        .azm-herder {
            background: #fff;
            height: 52*2upx;
            padding: 0 15*2upx;

            .azm-name {
                font-size: 13*2upx;
                font-weight: bold;
            }

            .azm-icon {
                font-size: 14*2upx;
                margin-left: 2*2upx;
            }

            .azm-close-icon {
                color: #cbd1d1;
                font-size: 14*2upx;
            }

            .azm-customize {
                font-size: 12*2upx;
            }

            .azm-tap-btns {
                .cu-btn {
                    margin-left: 7*2upx;
                    height: 24*2upx;
                    border-radius: 3*2upx;
                    font-size: 10*2upx;
                    font-weight: 500;
                    padding: 0 7*2upx;

                    &.bg-gray {
                        background: #F6F6F6;
                        color: #B0B6BC;
                    }
                }
            }
        }

        .azm-top {
            .cu-item {
                height: auto;
                line-height: inherit;
                padding: 10*2upx 0;

                &:nth-child(1) {
                    padding-left: 15*2upx;
                    margin-left: 0;
                }
            }
        }

        .azm-tabs-item {
            color: #8B8B8B;
            height: 24*2upx;
            padding: 0 8*2upx;
            font-size: 12*2upx;

            &.active {
                background: #F1F1F1;
                color: #47484A;
                font-weight: bold;
            }
        }

        .azm-txt-right, .azm-txt-left {
            font-size: 10*2upx;
            color: #A2A8A8;
        }

        .azm-txt-left {
            padding-left: 15*2upx;
            width: 40*2upx;
            text-align: center;
        }

        .azm-txt-right {
            padding-right: 15*2upx;
        }

        .azm-rank > .cu-item {
            height: 76*2upx;

            .cu-avatar {
                width: 40*2upx;
                height: 40*2upx;
                margin-right: 8*2upx;
            }

            .azm-avatar {
                width: 100%;
                height: 100%;
                border-radius: 100%;
            }

            .content {
                .azm-nickname {
                    height: 20*2upx;
                    font-size: 16*2upx;
                    font-weight: bold;
                    line-height: 20*2upx;
                }

                .azm-desc {
                    margin-top: 4*2upx;
                    height: 16*2upx;
                    font-size: 11*2upx;
                    color: #6B6B6B;
                    line-height: 16*2upx;
                }
            }

            .action {
                text-align: right;
                max-width: 120*2upx;

                .azm-num {
                    font-size: 18*2upx;
                    font-weight: bold;
                    height: 20*2upx;
                    line-height: 20*2upx;
                    font-family: DINAlternate-Bold, DINAlternate;
                }

                .azm-sort {
                    margin-top: 4*2upx;
                    font-size: 10*2upx;
                    color: #A2A8A8;
                    height: 16*2upx;
                    line-height: 16*2upx;
                }
            }
        }
    }
</style>
